package com.bjc.scheduler.elasticjob.springboot.service;

import com.bjc.scheduler.elasticjob.springboot.model.FileCustom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: elastic-job-springboot
 * @description:
 * @author: bjc
 * @create: 2021-08-15 21:46
 */
@Service
public class FileService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取某文件类型未备份的文件
     * @param fileType
     * @param count
     * @return
     */
    public List<FileCustom> fetchUnBackupFiles(String fileType,Integer count){
        String sql = "select * from t_file where type =? and backedUp = 0 limit 0,?";
        List<FileCustom> files = jdbcTemplate.query(sql, new Object[]{fileType, count}, new BeanPropertyRowMapper<>(FileCustom.class));
        return files;
    }

    public void backupFiles(List<FileCustom> files){
        files.forEach(file->{
            String sql = "update t_file set backedUp = 1 where id = ?";
            jdbcTemplate.update(sql,new Object[]{file.getId()});
            System.out.println(String.format("线程%d | 已备份文件:%s  文件类型:%s",Thread.currentThread().getId()
            ,file.getName(),file.getType()));
        });
    }
}
